package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JwtUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token==null){
            token = request.getParameter("token");
        }
        if (StringUtils.isNoneBlank(token)){
            Claims claims = JwtUnit.checkJwt(token);
            if(claims == null){
                CommonUtil.responseJson(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            long id = Long.valueOf(claims.get("id").toString());
            String name = claims.get("name").toString();
            String headImg = claims.get("head_img").toString();
            String mail = claims.get("mail").toString();
            LoginUser loginUser = LoginUser.builder().id(id)
                    .name(name).headImg(headImg).mail(mail).build();
            //request.setAttribute("LOGINUSER",loginUser);
            threadLocal.set(loginUser);
            return true;
        }else{
            CommonUtil.responseJson(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
